<!--
 * @Author: 1453937336@qq.com 1453937336@qq.com
 * @Date: 2024-04-18 18:37:23
 * @LastEditors: 1453937336@qq.com 1453937336@qq.com
 * @LastEditTime: 2024-07-10 10:47:09
 * @FilePath: \itforce-hris\src\pages\organization\components\unit-modal.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <a-modal v-model:open="open" :title="$t('职位')" @cancel="handleColse" :maskClosable="false">
      <a-form layout="vertical" :model="formState" ref="formRef" style="margin-top: 24px;">
        <a-row :gutter="[16,0]">
          <a-col :span="12">
            <a-form-item :label="$t('positionTitle')" name="name" :rules="[{ required: true, message: $t('请输入') }]">
              <a-input v-model:value="formState.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('缩写')" name="shortName" :rules="[{ required: true, message: $t('请输入') }]">
              <a-input v-model:value="formState.shortName" maxlength="20"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('PositionEmail')" name="email" :rules="[
              {
                required: false,
                pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                message: $t('邮箱格式不正确')
              }
            ]">
              <a-input v-model:value="formState.email" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('人数')">
              <a-input v-model:value="formState.headCount" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('电话')">
              <a-input v-model:value="formState.phone" />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item :label="$t('等级')">
              <a-select ref="select" v-model:value="formState.levelId" :placeholder="$t('请选择')">
                <a-select-option v-for="(item, index) in props.levelList" :value="item.dictData">{{ `${item.dictData} - ${item.dictDesc}` }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-item :label="$t('类别')">
              <a-select ref="select" v-model:value="formState.category" :placeholder="$t('请选择')" @change="categoryChange">
                <a-select-option v-for="(item, index) in props.categoryList" :value="item.dictData">{{ isCn ? item.descZh : isArabic ? item.descAr : item.dictDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12"  v-if="formState.category === '3'">
            <a-form-item :label="$t('Service Order')">
              <a-select
                v-model:value="formState.soId"
                show-search
                style="width: 100%"
                :placeholder="$t('请选择')"
                :options="serviceOrderList"
                :filter-option="serviceOrderFilterOption"
                :fieldNames="{
                  value: 'id',
                  label: 'name'
                }"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('岗位人员类型')" name="personalType" :rules="[{ required: true, message: $t('请选择') }]">
              <a-select ref="select" v-model:value="formState.personalType" :placeholder="$t('请选择')">
                <a-select-option v-for="(item, index) in props.positionPersonalTypeList" :value="item.dictData">{{ isCn ? item.descZh : isArabic ? item.descAr : item.dictDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('岗位类型')" name="positionType" :rules="[{ required: true, message: $t('请选择') }]">
              <a-select ref="select" v-model:value="formState.positionType" :placeholder="$t('请选择')" :disabled="formState.id">
                <a-select-option v-for="(item, index) in props.positionTypeList" :value="item.dictData">{{ isCn ? item.descZh : isArabic ? item.descAr : item.dictDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('薪酬水平')" name="salaryAmount" :rules="[
              { required: false, message: $t('请输入') },
              {
                  pattern: /^[0-9]*(\.[0-9]{1,2})?$/,
                  message: $t('请输入正确格式')
              }]">
              <a-input v-model:value="formState.salaryAmount"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item :label="$t('薪酬费率')">
              <a-select ref="select" v-model:value="formState.salaryRate" :placeholder="$t('请选择')">
                <a-select-option v-for="(item, index) in props.salaryRateList" :value="item.dictData">{{ isCn ? item.descZh : isArabic ? item.descAr : item.dictDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item :label="$t('倒班')">
              <a-select ref="select" v-model:value="formState.rotation" :placeholder="$t('请选择')">
                <a-select-option v-for="(item, index) in props.rotationList" :value="item.dictData">{{ isCn ? item.descZh : isArabic ? item.descAr : item.dictDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item :label="$t('组织')" name="buIdList" :rules="[{ required: true, message: $t('请选择') }]">
              <!-- <a-select
                ref="select"
                v-model:value="formState.buId"
                @change="selectChange"
                :getPopupContainer="
                  triggerNode => {
                    return triggerNode.parentNode || document.body;
                  }
                "
              >
                <a-select-option v-for="(item, index) in treeList" :key="index" :value="item.id">
                  <svg-icon :name="item.unitTypeIcon"/>{{ getLeve(item.level) }}{{ isCn ? item.nameZh : isArabic ? item.nameAr : item.nameEn }}
                </a-select-option>
              </a-select> -->
              <a-cascader
                v-model:value="formState.buIdList"
                :options="treeData"
                placeholder="Please select"
                change-on-select
                :fieldNames="{
                  children: 'children',
                  value: 'id',
                  label: isCn ? 'nameZh' : isArabic ? 'nameAr' : 'nameEn'
                }"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('汇报')">
              <a-cascader v-model:value="formState.reportBuIdList" style="width: 60%" :placeholder="$t('请选择')" :options="treeList"
                :fieldNames="{
                  children: 'children',
                  label: isCn ? 'nameZh' : isArabic ? 'nameAr' : 'nameEn',
                  value: 'id'
                }" @change="cascaderChange" change-on-select />
              <a-select
                v-model:value="formState.reportTo"
                show-search
                style="width: 40%"
                :token-separators="[',']"
                :placeholder="$t('请选择')"
                :options="lineManagerOptions"
                :filter-option="filterOption"
                :fieldNames="{
                  // label: 'name',
                  value: 'id',
                  label: 'fullName'
                }"
              >
              </a-select>
              <!-- <a-select ref="select" show-search v-model:value="formState.reportTo" :placeholder="$t('请选择')">
                <a-select-option v-for="(item, index) in lineManagerOptions" :value="item.id" :disabled="item.id === formState.id"  :filter-option="filterOption">{{ item.name }} ({{ getListName(item.positionType, props.positionTypeList) }})</a-select-option>
              </a-select> -->
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('描述')"  prop="description">
              <a-textarea v-model:value="formState.description" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('能力')">
              <a-textarea v-model:value="formState.capability" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('资格')">
              <a-textarea v-model:value="formState.qualification" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-button style="font-size: 12px;" :loading="loading" @click="handleColse">{{ $t('关闭') }}</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">{{ $t('保存') }}</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
  import { Modal, message } from 'ant-design-vue';
  import { useI18n } from 'vue-i18n';
  const { t: $t } = useI18n();
  import { useLanguage } from "@/hooks/index";
  const { isEn, isCn, isArabic } = useLanguage();
  import { GetPositionList, GetBusinessUnitTree, PostPositionAdd, GetPositionUuid, GetPositionInfo, GetOrganizationServiceOrderPage } from "@/api/organization/index";
  import { findAllParents } from '@/utils/common/common'
  const emits = defineEmits(['refreshList'])
  const props = defineProps({
    levelList: {
      type: Array,
      default: [],
    },
    categoryList: {
      type: Array,
      default: [],
    },
    companyId: {
      type: String,
      default: '',
    },
    positionTypeList: {
      type: Array,
      default: [],
    },
    positionPersonalTypeList: {
      type: Array,
      default: [],
    },
    rotationList: {
      type: Array,
      default: [],
    },
    salaryRateList: {
      type: Array,
      default: [],
    }
  });
  const formState = ref({
    name: '',
    shortName: '',
    description: '',
    buId: '',
    buIdList: '',
    reportTo: undefined,
    reportBuId: undefined,
    reportBuIdList: undefined,
    capability: '',
    qualification: '',
    headCount: '',
    email: '',
    phone: '',
    levelId: undefined,
    category: undefined,
    soId: undefined,
    personalType: undefined,
    positionType: undefined,
    salaryAmount: null,
    salaryRate: undefined,
    rotation: undefined,
    id: undefined
  });

  const categoryChange = (val: any) => {
    formState.value.category = val
    if (val === '3') {
      getServiceOrderList()
    }
  }
  const serviceOrderList = ref([])
  const getServiceOrderList = async () => {
    const { data } = await GetOrganizationServiceOrderPage({enterpriseId: companyId.value})
    serviceOrderList.value = data
  }

  const open = ref(false);
  const loading = ref(false);
  const companyId = ref()
  const showModal = (id: any, record: { id: any; uuid: any; }) => {
    open.value = true
    companyId.value = id
    getTree(id)
    getPositionList()
    if (record?.id) {
      getPositionInfo(record.uuid)
    }
  }
  const getListName = (val: any, codeValue: any) => {
    let name = null;
    let obj = null;
    if (val || val === 0) {
      obj = codeValue.find((item: any) => {
        if (item.dictData == String(val)) return item;
      });
      name = isCn.value ? obj?.descZh : isArabic.value ? obj?.descAr : obj?.dictDesc;
    }
    return name;
  };
  const getPositionInfo = async (uuid: any) => {
    const { data } = await GetPositionInfo(uuid)
    formState.value = cloneDeep(data)
    
    formState.value.buIdList = findAllParents(treeData.value, formState.value.buId)
    formState.value.reportBuIdList = findAllParents(treeList.value, formState.value.reportBuId)
    // formState.value.lineManager = (data.lineManagerName && data.lineManagerName.split(",")) || undefined
    formState.value.levelId = data.levelId ? String(data.levelId) : undefined
    formState.value.category = data.category ? String(data.category) : undefined
    formState.value.personalType = (data.personalType || data.personalType === 0) ? String(data.personalType) : undefined
    formState.value.positionType = (data.positionType || data.positionType === 0) ? String(data.positionType) : undefined
    formState.value.salaryRate = (data.salaryRate || data.salaryRate === 0) ? String(data.salaryRate) : undefined
    formState.value.rotation = (data.rotation || data.rotation === 0) ? String(data.rotation) : undefined
    formState.value.reportTo = Number(data.reportTo) || undefined
    formState.value.soId = Number(data.soId) || undefined
  }

  const cascaderChange = (val: any) => {
    formState.value.reportBuId = val[val.length - 1]
    formState.value.reportTo = undefined
    getPositionList()
  }

  const lineManagerOptions = ref([])
  const getPositionList = async () => {
    const { data }: any = await GetPositionList({ enterpriseId: props.companyId, buId: formState.value.reportBuId, positionType: 1 });
    lineManagerOptions.value = data.map((item: { name: any; positionType: any; }) => {
      return {
        ...item,
        fullName: `${item.name}  (${getListName(item.positionType, props.positionTypeList)})`,
      }
    }) || []
  }
  const isDisabled = computed((val) => {
    return formState.value.id === val
  })
  const treeData = ref([])
  const treeLevels = ref([])
  const treeList = ref([])
  const getTree = (id: any) => {
    GetBusinessUnitTree({
      enterpriseId: id
    }).then(res => {
      treeData.value = convertValuesToString(res.data)
      // treeLevels.value = addLevels(treeData.value)
      // treeList.value = flattenTree(treeData.value)
      treeList.value = treeData.value[0].children
    })
  }
  const convertValuesToString = (tree) => {
    return tree.map((node) => {
      const convertedNode = { ...node };
      if (convertedNode.children) {
        convertedNode.children = convertValuesToString(convertedNode.children);
      }
      convertedNode.nameZh = isCn && convertedNode.nameZh ? convertedNode.nameZh : convertedNode.nameEn
      convertedNode.nameAr = isArabic && convertedNode.nameAr ? convertedNode.nameAr : convertedNode.nameEn
      return convertedNode;
    });
  };
  // const getLeve = (num: number) => {
  //   let dotted = ' '
  //   let dashedLine = '----';
  //   let numOfDashes = num > 0 ? num * 4 : 0;
  //   for (let i = 0; i < numOfDashes; i += 4) {
  //       dotted += dashedLine
  //   }
  //   return dotted
  // }
  //  // 添加层级标记
  // const addLevels = (nodes: any[], level = 0) => {
  //   return nodes.map((node: { level: number; children: string | any[]; }) => {
  //     node.level = level;
  //     if (node.children && node.children.length > 0) {
  //       node.children = addLevels(node.children, level + 1);
  //     }
  //     return node;
  //   });
  // }
  // // 平铺树形结构
  // const flattenTree = (tree: never[], parentId = null) => {
  //   let flattened = [];
  //   for (let node of tree) {
  //     const cloned = {...node, parentId};
  //     delete cloned.children; // 删除children属性，以便可以直接添加到结果数组中
  //     flattened.push(cloned);
  //     if (node.children && node.children.length > 0) {
  //       // 递归处理子节点
  //       flattened = flattened.concat(flattenTree(node.children, node));
  //     }
  //   }
  //   return flattened;
  // }
  const handleColse = () => {
    open.value = false
    formRef.value.resetFields();
    formState.value = {}
  }
  const formRef = ref(null);
  const handleOk = debounce(() => {
    loading.value = true
    console.log('ddddd', formState.value)
    formState.value.buId = formState.value.buIdList[formState.value.buIdList.length - 1]
    formRef.value.validate().then(() => {
      if (formState.value.id) {
        GetPositionUuid({
          ...formState.value,
          enterpriseId: companyId.value
        }).then(res => {
          loading.value = false
          message.success($t('操作成功'));
          handleColse()
          emits('refreshList')
        }).finally(() => {
          loading.value = false
        });
      } else {
        PostPositionAdd({
          ...formState.value,
          enterpriseId: companyId.value
        }).then(res => {
          loading.value = false
          message.success($t('操作成功'));
          handleColse()
          emits('refreshList')
        }).finally(() => {
          loading.value = false
        });
      }
    }).catch((error: any) => {
      loading.value = false
      // consoleerror('验证失败:', error);
    });
  }, 1000);

  const filterOption = (input: string, option: any) => {
    return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  const serviceOrderFilterOption = (input: string, option: any) => {
    return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  // const lineManagerChange = (v: string | any[]) => {
  //   const list = lineManagerOptions.value.filter(item => v.includes(item.id))
  //   formState.value.lineManagerId = list.map(item => item.id).join(',')
  //   formState.value.lineManagerName = list.map(item => item.fullName).join(',')
  // }
  
  function findAncestors(tree: any, targetId: any) {
    const ancestors: never[] = [];
  
    function findAncestor(nodes: any[], targetId: any) {
      nodes.forEach((node: { id: any; children: string | any[]; }) => {
        if (node.id === targetId) {
          ancestors.value.push(node);
          return;
        }
        if (node.children && node.children.length > 0) {
          findAncestor(node.children, targetId);
          if (ancestors.value.length > 0) {
            ancestors.value.push(node);
          }
        }
      });
    }
    findAncestor([tree], targetId);
    return ancestors.value;
  }
  defineExpose({
    showModal
  });
</script>
<style lang="scss" scoped>
.saveButton {
  background-color: #ff6700;
  color: #fff;
  font-size: 12px;
}
.saveButton:active {
  color: #fff;
  border-color: #fff;
}
.saveButton:hover {
  color: #fff;
  border-color: #fff;
}
.ant-btn {
  font-size: 12px;
}
::v-deep {
  // .ant-form-item {
  //   margin-bottom: 0;
  //   font-size: 12px;
  // }
}
</style>
